#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/wait.h>

/* Define mutex */
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;

int main()
{
    int i = 0;
    pid_t pid;
    pthread_mutex_t *m_mutex;

    /* mutex attr Initialization */
    pthread_mutexattr_init(&mutexattr);
        
    /* modify attribute */
    pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED);

    /* mutex Initialization */
    pthread_mutex_init(&mutex, &mutexattr);

    /* Share mutex */
    m_mutex  = (pthread_mutex_t*) mmap(NULL, sizeof(mutex), PROT_READ|PROT_WRITE,
                                        MAP_SHARED|MAP_ANON, -1, 0);

    pid = fork();

    if(pid == 0){
        for(; i<3; i++){
            sleep(1);
            pthread_mutex_lock(m_mutex);
            puts("This is the child process!");
            pthread_mutex_unlock(m_mutex);
        }           
    }else
    {
        for(; i<3; i++){
            sleep(1);
            pthread_mutex_lock(m_mutex);
            puts("This is the parent process!");
            pthread_mutex_unlock(m_mutex);
        }

        /* Recycle subprocess resources */
        wait(NULL); 
    }
    
    /* Destroy mutex */
    pthread_mutexattr_destroy(&mutexattr);
    pthread_mutex_destroy(&mutex);
    
    /* Cancel mapping */
    munmap(m_mutex, sizeof(mutex)); 

    return 0;
}
